﻿using System;
using System.Security.Permissions;
using System.Web.UI.WebControls;
using System.Transactions;
using System.Configuration;
using MakeItWeb.Framework;

namespace AllNations.WebAppAdmin
{
    public partial class PhotoManager : MakeItWeb.Framework.MakeItWebAdminPage
    {
        Guid _PhotoalbumId = Guid.Empty;
        MakeItWeb.Framework.Photoalbum _Photoalbum = null;

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            if (!string.IsNullOrEmpty(Request.QueryString["PhotoalbumId"]))
            {
                _PhotoalbumId = new Guid(Request.QueryString["PhotoalbumId"]);
                _Photoalbum = MakeItWeb.Framework.Photoalbum.GetPhotoalbum(_PhotoalbumId);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (_Photoalbum != null && _Photoalbum.Loaded)
            {
                PhotoManViews.SelectedIndex = 1;
            }

            if (Request.QueryString["Page"] == "Create")
            {
                PhotoManViews.SelectedIndex = 2;
                btCancelCreate.OnClientClick = "location='/WebAppAdmin/PhotoManager.aspx{0}'; return false;";
            }
            else if (Request.QueryString["Page"] == "Featured")
            {
                PhotoManViews.SelectedIndex = FeaturedPhotoView.Index;
                if (!IsPostBack)
                {
                    RefreshFeaturedPhotoList();
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            switch (PhotoManViews.SelectedIndex)
            {
                case 0:
                    dlPhotoalbum.DataSource = MakeItWeb.Framework.Photoalbum.ListPhotoalbum(CurrentHtmlPage.HtmlPageId, true);
                    dlPhotoalbum.DataBind();
                    lnkManager.Text = "+ Create Album";
                    lnkManager.NavigateUrl = string.Format("/WebAppAdmin/PhotoManager.aspx?HtmlPageId={0}&Page=Create", Request["HtmlPageId"]);
                    break;
                case 1:
                    panelAddPhoto.Visible = !_Photoalbum.ArchiveInd;
                    txtTitle.Text = _Photoalbum.TitleTxt;
                    cbArchiveInd.Checked = _Photoalbum.ArchiveInd;
                    rptPhoto.DataSource = _Photoalbum.AlbumPhotos;
                    rptPhoto.DataBind();
                    lnkManager.Text = "&lt; Back to list";
                    lnkManager.NavigateUrl = string.Format("/WebAppAdmin/PhotoManager.aspx?HtmlPageId={0}", Request["HtmlPageId"]);
                    break;
                case 2:
                    // clear all fields
                    txtTitleNew.Text = string.Empty;
                    break;
            }
        }
        protected void btSaveAlbum_Click(object sender, EventArgs e)
        {
            _Photoalbum.TitleTxt = txtTitle.Text.Trim();
            _Photoalbum.ArchiveInd = cbArchiveInd.Checked;
            _Photoalbum.Save();
        }
        protected void btAddPhotoToAlbum_Click(object sender, EventArgs e)
        {
            if (fuPhoto.UploadedFiles.Count > 0)
            {
                string sRoot = string.Format(@"{0}\{1}", Server.MapPath(ConfigurationManager.AppSettings["PhotoRoot"]), _PhotoalbumId);
                if (!System.IO.Directory.Exists(sRoot))
                    System.IO.Directory.CreateDirectory(sRoot);

                Guid guidLastPhotoId = Guid.Empty;
                foreach (Telerik.Web.UI.UploadedFile file in fuPhoto.UploadedFiles)
                {
                    string sFileName = file.FileName.Substring(file.FileName.LastIndexOf(@"\") + 1);
                    string sImgFilename = string.Format(@"{0}\{1}", sRoot, sFileName);
                    file.SaveAs(sImgFilename);
                    MakeItWeb.Framework.Photo photo = new MakeItWeb.Framework.Photo();
                    photo.PhotoId = Guid.NewGuid();
                    photo.PhotoalbumId = _PhotoalbumId;
                    photo.FilenameTxt = sFileName;
                    photo.FilepathTxt = sImgFilename;
                    photo.TitleTxt = string.Empty;
                    photo.DescTxt = string.Empty;
                    photo.FilesizeNum = file.ContentLength;
                    photo.Save();

                    guidLastPhotoId = photo.PhotoId;
                }

                if (guidLastPhotoId != Guid.Empty)
                {
                    _Photoalbum.LatestPhotoId = guidLastPhotoId;
                    _Photoalbum.Save();
                }

                Response.Redirect(Request.RawUrl, true);
            }
        }

        protected void btUpdatePhoto_Click(object sender, EventArgs e)
        {
            bool bDirty = false;
            foreach (RepeaterItem item in rptPhoto.Items)
            {
                MakeItWeb.Framework.Photo photo = MakeItWeb.Framework.Photo.GetPhoto(new Guid((item.FindControl("hidPhotoId") as HiddenField).Value));
                if (photo.Loaded)
                {
                    photo.TitleTxt = (item.FindControl("txtTitle") as TextBox).Text.Trim();
                    photo.DescTxt = (item.FindControl("txtDesc") as TextBox).Text.Trim();
                    if (photo.Dirty)
                        bDirty = true;
                    photo.Save();
                }
            }
            if (bDirty)
                Response.Redirect(Request.RawUrl, true);
        }

        protected void btUpdatePhoto_Click2(object sender, EventArgs e)
        {
            bool bDirty = false;
            foreach (RepeaterItem item in rptFeaturedPhoto.Items)
            {
                MakeItWeb.Framework.Photo photo = MakeItWeb.Framework.Photo.GetPhoto(new Guid((item.FindControl("hidPhotoId") as HiddenField).Value));
                if (photo.Loaded)
                {
                    photo.TitleTxt = (item.FindControl("txtTitle") as TextBox).Text.Trim();
                    photo.DescTxt = (item.FindControl("txtDesc") as TextBox).Text.Trim();
                    if (photo.Dirty)
                        bDirty = true;
                    photo.Save();
                }
            }
            if (bDirty)
                Response.Redirect(Request.RawUrl, true);
        }

        protected void btDeleteSel_Click(object sender, EventArgs e)
        {
            bool bDirty = false;
            foreach (RepeaterItem item in rptPhoto.Items)
            {
                if ((item.FindControl("cbSelect") as CheckBox).Checked)
                {
                    MakeItWeb.Framework.Photo photo = MakeItWeb.Framework.Photo.GetPhoto(new Guid((item.FindControl("hidPhotoId") as HiddenField).Value));
                    if (photo.Loaded)
                    {
                        try
                        {
                            System.IO.File.Delete(photo.FilepathTxt);
                        }
                        catch (Exception)
                        {
                            // surpress this one
                        }
                        if (_Photoalbum.LatestPhotoId == photo.PhotoId)
                        {
                            bool bNextFound = false;
                            foreach (MakeItWeb.Framework.Photo ph in _Photoalbum.AlbumPhotos)
                            {
                                if (ph.PhotoId != photo.PhotoId)
                                {
                                    _Photoalbum.LatestPhotoId = ph.PhotoId;
                                    bNextFound = true;
                                    break;
                                }
                            }
                            if (!bNextFound)
                                _Photoalbum.LatestPhotoId = Guid.Empty;

                            _Photoalbum.Save();
                        }
                        MakeItWeb.Framework.Photo.DeletePhoto(photo.PhotoId);
                        bDirty = true;
                    }
                }
            }
            if (bDirty)
                Response.Redirect(Request.RawUrl, true);
        }

        protected void btFeatureSel_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in rptPhoto.Items)
            {
                if ((item.FindControl("cbSelect") as CheckBox).Checked)
                {
                    MakeItWeb.Framework.Photo photo = MakeItWeb.Framework.Photo.GetPhoto(new Guid((item.FindControl("hidPhotoId") as HiddenField).Value));
                    if (photo.Loaded)
                    {
                        photo.FeaturedInd = true;
                        photo.Save();
                    }
                }
            }
        }

        protected void btUnFeatureSel_Click(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in rptFeaturedPhoto.Items)
            {
                if ((item.FindControl("cbSelect") as CheckBox).Checked)
                {
                    MakeItWeb.Framework.Photo photo = MakeItWeb.Framework.Photo.GetPhoto(new Guid((item.FindControl("hidPhotoId") as HiddenField).Value));
                    if (photo.Loaded)
                    {
                        photo.FeaturedInd = false;
                        photo.Save();
                    }
                }
            }
            RefreshFeaturedPhotoList();
        }

        private void RefreshFeaturedPhotoList()
        {
            rptFeaturedPhoto.DataSource = MakeItWeb.Framework.Photo.ListFeaturedPhotoAdmin();
            rptFeaturedPhoto.DataBind();
        }

        protected void btCreateAlbum_Click(object sender, EventArgs e)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                // save photo album information
                MakeItWeb.Framework.Photoalbum album = new MakeItWeb.Framework.Photoalbum();
                album.HtmlPageId = new Guid(Request.QueryString["HtmlPageId"]);
                album.PhotoalbumId = Guid.NewGuid();
                album.TitleTxt = txtTitleNew.Text.Trim();
                album.Save();

                // create photoalbum file directory
                string sRoot = string.Format(@"{0}\{1}", Server.MapPath(ConfigurationManager.AppSettings["PhotoRoot"]), _PhotoalbumId);
                if (!System.IO.Directory.Exists(sRoot))
                    System.IO.Directory.CreateDirectory(sRoot);

                Guid guidLastPhotoId = Guid.Empty;
                foreach (Telerik.Web.UI.UploadedFile file in fuPhotoNew.UploadedFiles)
                {
                    try
                    {
                        string sFileName = file.FileName.Substring(file.FileName.LastIndexOf(@"\") + 1);
                        string sImgFilename = string.Format(@"{0}\{1}", sRoot, sFileName);
                        file.SaveAs(sImgFilename);    // save the file in the file system
                        MakeItWeb.Framework.Photo photo = new MakeItWeb.Framework.Photo();
                        photo.PhotoId = Guid.NewGuid();
                        photo.PhotoalbumId = album.PhotoalbumId;
                        photo.FilenameTxt = sFileName;
                        photo.FilepathTxt = sImgFilename;
                        photo.TitleTxt = string.Empty;
                        photo.DescTxt = string.Empty;
                        photo.FilesizeNum = file.ContentLength;
                        photo.Save();

                        guidLastPhotoId = photo.PhotoId;
                    }
                    catch (Exception)
                    {
                    }
                }
                if (guidLastPhotoId != Guid.Empty)
                {
                    album.LatestPhotoId = guidLastPhotoId;
                    album.TitleTxt = txtTitleNew.Text.Trim();
                    album.Save();
                }

                scope.Complete();
            }
            Response.Redirect(string.Format("~/WebAppAdmin/PhotoManager.aspx?HtmlPageId={0}", Request.QueryString["HtmlPageId"]), true);
        }
    }
}